/*
 * jqDnR - Minimalistic Drag'n'Resize for jQuery.
 *
 * Copyright (c) 2007 Brice Burgess <bhb@iceburg.net>, http://www.iceburg.net
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * $Version: 2007.08.19 +r2
 */

(function ($){

	$.fn.jqDrag=function (handle, proxy, cb){
		return i(this,handle,'drag', proxy, cb);
	};

	$.fn.jqResize=function (handle, proxy, cb){
		return i(this,handle,'resize', proxy, cb);
	};

	var dnr={}, E, use_proxy, obj_proxy, stop_cb, pos={};

	$.jqDnR={
		drag:function (ev){
			if (use_proxy && !obj_proxy){
				$(document.body).append('<div id="jqDnR_move" style="position:absolute; border:1px dotted #000; background:#ccc; opacity:0.5; filter:alpha(opacity=50)"></div>');
				obj_proxy = $("#jqDnR_move");
				obj_proxy.css({left:dnr.X, top:dnr.Y, width:dnr.W, height:dnr.H, zIndex:(dnr.zIndex+1)});
			}

			pos = dnr.kind=='drag' ? { left:dnr.X+ev.pageX-dnr.pX,top:dnr.Y+ev.pageY-dnr.pY }
								   : { width:Math.max(ev.pageX-dnr.pX+dnr.W,0),height:Math.max(ev.pageY-dnr.pY+dnr.H,0) };
			if (obj_proxy)obj_proxy.css(pos);
			else E.css(pos);
			return false;
		},

		stop:function (ev){
			if (obj_proxy) obj_proxy.remove();

			if (stop_cb)stop_cb(pos);
			else E.css(pos);

			pos = {};
			dnr={};
			E = null;
			use_proxy = false;
			obj_proxy = null;
			stop_cb = null;
			$().unbind('mousemove',$.jqDnR.drag).unbind('mouseup',$.jqDnR.stop);
		}
	};

	function i(obj, handle, kind, proxy, cb){
		return obj.each(function (){
			handle=(handle)?$(handle,obj):obj;
			handle.bind('mousedown',{obj:obj,kind:kind,proxy:proxy,cb:cb},function (ev){
				var d=ev.data,p={};
				stop_cb = cb;

				E=d.obj;
				if(E.css('position')!='relative'){
					try{
						p = E.position();
					}catch(e){}
				}

				dnr={
					X:p.left||getCss('left')||0,
					Y:p.top||getCss('top')||0,
					//W:getCss('width')||E[0].scrollWidth||0,
					//H:getCss('height')||E[0].scrollHeight||0,
					W:E.width(),
					H:E.height(),
					pX:ev.pageX,
					pY:ev.pageY,
					kind:d.kind,
					zIndex:E.css('z-index')
				};

				use_proxy = d.proxy;

				$().mousemove($.jqDnR.drag).mouseup($.jqDnR.stop);
				return false;
			});

		});

	}

	getCss=function (kind){
		return parseInt(E.css(kind))||false;
	};

})(jQuery);
